import productbaseApi from "@/api/productbase";
import EnvironmentForm from "./form/environmentForm";
import CompanyForm from "./form/companyForm";
import VDistpicker from 'v-distpicker';
import qs from "qs";
import AddNew from "./form/editForm.vue";
import VueElementLoading from 'vue-element-loading';
import { hasPermissionPoint } from "@/utils/permission";

const BASEURL = "https://image.zysuyuan.cn:8031/";
// import {
//   BaiduMap,
//   BmScale,
//   BmNavigation,
//   BmOverviewMap,
//   BmCityList,
//   BmMarker,
//   BmControl,
//   BmView,
//   BmAutoComplete,
//   BmLocalSearch
// } from "vue-baidu-map";

// 基地面积
const baseArea = [
    { type: "1", name: "≥100亩", value: "100" },
    { type: "2", name: "≥500亩", value: "500" },
    { type: "3", name: "≥1000亩", value: "1000" },
    { type: "4", name: "≥5000亩", value: "5000" },
    { type: "5", name: "≥10000亩", value: "10000" }
];
// 药材，用来测试
const mnames = [
    { type: "1", name: "化橘红" },
    { type: "2", name: "沉香" },
    { type: "3", name: "阳春砂" },
    { type: "4", name: "何首乌" },
    { type: "5", name: "巴戟天" },
    { type: "6", name: "广陈皮" },
    { type: "7", name: "广佛手" },
    { type: "8", name: "广藿香" }
];

const components = {
    EnvironmentForm,
    CompanyForm,
    VDistpicker,
    AddNew,
    VueElementLoading
};

const data = function () {
    return {
        enviroform: {
            bWaterEnvironment: "",
            bSoilEnvironment: "",
            bAirEnvironment: "",
            bTotalityAppraise: "",
            bEnvironmentDataImgPath: ""
        },
        companyform: {
            bCompanyName: "",
            bCompanyPosition: "",
            bCompanyPerson: "",
            bCompanyContact: "",
            bCompanyMedicinal: "",
            bCompanyRemarks: ""
        },
        // 百度地图
        center: { lng: 0, lat: 0 },
        // 图片展示类型
        fit: "contain",
        zoom: 3,
        // 调整装备
        locData: {
            ids: 0, //设置定位id
            longitude: "", //设置定位经度
            latitude: "" //设置定位纬度
        },
        options: [
            {
                value: "选项1",
                label: "省"
            },
            {
                value: "选项2",
                label: "市"
            },
            {
                value: "选项3",
                label: "区"
            }
        ],
        value: "",
        dialogTableVisible: false,
        dialogFormVisible: false,
        editdataDialog: false, // 编辑产地产区基地弹窗
        positionDialog: false, // 选择位置弹窗
        dialogEnviroForm: false, //生态环境弹窗
        dialogFormGps: false, //gps弹窗
        dialogbaseArea: false, //基地照片弹窗
        dialogCompanyForm: false, //公司详情弹窗
        dialogUploadPhoto: false, //上传图片弹窗
        dialogImageUrl: "",
        dialogupPhoto: false, // 上传图片弹窗2
        formLabelWidth: "120px",
        radio: null, // 如果使用单选框，定义一个model值
        currentSelectItem: {}, //当前选中的值
        list: [],
        mNameList: [],  // 药材名称列表
        imgs: [],
        total: 0, //总记录数
        currentPage: 1, //当前页码
        pageSize: 5, //每页显示10条数据
        searchMap: {
            page: "",
            size: "",
            bName: "", // 基地名称
            bInputLocation: "", // 基地地址
            mName: "", //生产药材
            bArea: "", // 基地面积
            bProvinceSeek: "", // 省
            bCitySeek: "", //市
            bRegionSeek: "" //区
        },
        position: "",
        location: '',
        keyword: '',  //搜索框关键词
        baseArea, // 基地面积
        mnames, // 药材名称
        BASEURL,
        maplocation: {
            // 百度地图经纬度
            latitude: "", // 维度
            longitude: "" // 经度
        },
        // 省市区
        province: null,
        city: null,
        area: null,
        placeholders: {
            province: '------- 省 --------',
            city: '--- 市 ---',
            area: '--- 区 ---',
        },
        fpojo: {
            id: "",
            bName: "",
            bArea: "",
            bCompanyId: "",
            bPosition: "",
            bProvince: "",
            bCity: "",
            bRegion: "",
            // 以下的省市区用来清空
            province: '',
            city: '',
            area: '',
            bLatitude: "",
            bLongitude: "",
            bRemarks: "",
            bWaterEnvironment: "",
            bSoilEnvironment: "",
            bAirEnvironment: "",
            bTotalityAppraise: "",
            bEnvironmentDataImgPath: ""
        },
        backup: {},
        backup2: {},
        fpojoCopy: {},
        isEdit: false,
        title: "",       // 弹窗标题
        fileList: [],
        files: []
    };
};

const methods = {
    btnshow(point) {
        return hasPermissionPoint(point);
    },
    chooseone(row) {
        this.radio = row.id;
        this.backup = row;
        this.backup2 = row;
    },
    handleSizeChange(val) {
        console.log(`每页${val}条`);
        this.pageSize = val;
        this.fetchData();
    },

    handleCurrentChange(val) {
        console.log(`当前页：${val}`);
        this.currentPage = val;
        this.fetchData();
    },

    fetchData() {
        this.searchMap.page = this.currentPage;
        this.searchMap.size = this.pageSize;
        // console.log(this.searchMap);
        var vm = this.$store;
        vm.commit('updateLoading', true);
        console.log('是否开启加载', this.$store.state.elementloading.vueElementLoading)
        productbaseApi.selectList(this.searchMap).then(resp => {
            // console.log(resp.data.rows);
            this.list = resp.data.rows;
            if (resp.data.rows) {
                vm.commit('updateLoading', false);
                console.log('是否开启加载', this.$store.state.elementloading.vueElementLoading)
            }
            // this.radio = this.list[0].id;
            this.maplocation.latitude = this.list[0].bLatitude;
            this.maplocation.longitude = this.list[0].bLongitude;
            console.log(resp);
            this.total = resp.data.total;
        });
        productbaseApi.selectAllMedicinal().then(resp => {
            this.mNameList = resp.data;
            console.log(this.mNameList);
        })
    },

    // 绑定查询按钮
    searchBase() {
        this.currentPage = 1;
        this.fetchData();
    },

    handleSelectionChange(row) {
        console.log(row);
        this.currentSelectItem = row;
    },
    // 弹出生态环境
    openenvironment(row) {
        this.enviroform.bWaterEnvironment = row.bWaterEnvironment;
        this.enviroform.bSoilEnvironment = row.bSoilEnvironment;
        this.enviroform.bAirEnvironment = row.bAirEnvironment;
        this.enviroform.bTotalityAppraise = row.bTotalityAppraise;
        console.log(this.enviroform);
        this.dialogEnviroForm = true;
    },
    //弹出gps窗口
    showgps(row) {
        console.log(row);
        this.center.lng = row.bLongitude;
        this.center.lat = row.bLatitude;
        console.log("经度:" + this.center.lng);
        console.log("纬度:" + this.center.lat);
        this.zoom = 15;
        this.dialogFormGps = true;
        this.$nextTick(() => {
            this.zoom = 15;
        })
    },
    uploadphotos() {
        this.dialogUploadPhoto = true;
    },

    // 弹出公司详情
    openCompany(row) {
        this.companyform.bCompanyName = row.bCompanyName;
        this.companyform.bCompanyPosition = row.bCompanyPosition;
        this.companyform.bCompanyPerson = row.bCompanyPerson;
        this.companyform.bCompanyContact = row.bCompanyContact;
        this.companyform.bCompanyMedicinal = row.bCompanyMedicinal;
        this.companyform.bCompanyRemarks = row.bCompanyRemarks;
        this.dialogCompanyForm = true;
    },
    // 百度地图方法
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(val) {
        var i = 0,
            valLen = val.length;

        if (valLen == 0) {
            this.locData.ids = 0;
        } else {
            for (i; i < valLen; i++) {
                if (i == 0) {
                    this.locData.ids = val[i].id;
                } else if (i > 0) {
                    this.locData.ids += "," + val[i].id;
                }
            }
        }
    },

    // 设置定位弹出框
    setLoc(formName) {
        if (this.locData.ids == 0) {
            this.$message({
                message: "请选中装备后再设置定位",
                type: "warning"
            });
        } else {
            this.dialogFormGps = true;
            map.clearOverlays();
        }
    },
    // 百度地图
    mapReady({ BMap, map }) {
        // this.center.lng = this.maplocation.longitude;
        // this.center.lat = this.maplocation.latitude;
        this.zoom = 15;
        window.map = map; //将map变量存储在全局
    },
    // positionReady({map}) {
    //     this.position.lng = 116.397128;
    //     this.position.lat = 39.916527;
    //     this.zoom = 15;
    //     window.map = map; //将map变量存储在全局
    // },
    // 地图点击事件
    getClickInfo(e) {
        map.clearOverlays();
        var myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat));
        map.addOverlay(myMarker);
        this.zoom = e.target.getZoom()
        this.locData.longitude = e.point.lng;
        this.locData.latitude = e.point.lat;
        this.center.lng = e.point.lng;
        this.center.lat = e.point.lat;
        // this.fpojo.bLongitude = e.point.lng;
        // this.fpojo.bLatitude = e.point.lat;
    },
    // 设置定位确认
    locSubmit(formName) {
        if (this.locData.longitude == "") {
            addOper.$message({
                message: "请单击地图设置定位后再提交",
                type: "warning"
            });
        } else {
            //  向后台提交locData数据
        }
        this.dialogFormGps = false;
    },
    // 设置定位取消
    locCancle(formName) {
        map.clearOverlays();
        this.dialogFormGps = false;
    },
    // 查看基地照片
    openbasephoto(row) {
        var vm = this.$store;
        vm.commit('updateImgLoading', true);
        console.log('是否开启加载', this.$store.state.elementloading.imgLoading)
        productbaseApi.selectImgsList(row.id).then(resp => {
            this.imgs = resp.data.rows;
            console.log(this.imgs);
            if (resp.data.rows) {
                vm.commit('updateImgLoading', false);
                console.log('是否开启加载', this.$store.state.elementloading.imgLoading)
            }
        });
        this.dialogbaseArea = true;
    },
    // 关闭查看基地图片t弹窗
    closeImgs() {
        this.imgs = [];
        this.dialogbaseArea = false;
    },
    // 关闭图片弹窗之前的回调,及点击弹窗右上角叉叉关闭按钮之前的回调方法
    // 为了将图片数组清空，弹窗滚轮置顶
    imgsDialogClose() {
        this.imgs = [];
        this.dialogbaseArea = false;
    },
    handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
    },
    // 显示搜索的条件
    searchproductBase() {
        console.log(this.searchMap);
    },
    handleChangeDis() {
        let selectFirst = document.getElementById('distpicker-warpper');
        let selectAll = selectFirst.getElementsByTagName('select');
        // selectAll[1].style.color =  '#c0c4cc';
        for (var a = 0; a < selectAll.length; a++) {
            var selectEle = selectAll[a];
            selectEle.style.color = '#c0c4cc'; // 文字颜色
            // document.getElementById('select-dis').getElementsByTagName('select')[1][0].style.color = '#c0c4cc';
            // document.getElementById('select-dis').getElementsByTagName('select')[1][0].style.color = '#c0c4cc';
            selectEle.style.borderColor = '#d9d9d9'; // 边框颜色
        }
    },
    // 获取省市区的值
    handleProvince(data) {
        // 修改选中文字颜色
        // document.getElementById('distpicker-warpper').getElementsByTagName('select')[0].style.color = '#606266';
        document.getElementById('select-dis').firstChild.style.color = '#606266';
        // 赋值给变量
        this.searchMap.bProvinceSeek = data.value.slice(0, data.value.length - 1);
        if (this.searchMap.bProvinceSeek == '省') {
            this.searchMap.bProvinceSeek = "";
        }
        console.log("省：" + this.searchMap.bProvinceSeek);
    },
    handleCity(data) {
        // 修改选中文字颜色
        document.getElementById('select-dis').getElementsByTagName('select')[1].style.color = '#606266';
        // 赋值给变量
        this.searchMap.bCitySeek = data.value.slice(0, data.value.length - 1);
        if (this.searchMap.bCitySeek == '市') {
            this.searchMap.bCitySeek = "";
        }
        console.log("市：" + this.searchMap.bCitySeek);
    },
    handleArea(data) {
        // 修改选中文字颜色
        document.getElementById('select-dis').getElementsByTagName('select')[2].style.color = '#606266';
        // 赋值给变量
        this.searchMap.bRegionSeek = data.value.slice(0, data.value.length - 1);
        if (this.searchMap.bRegionSeek == '区') {
            this.searchMap.bRegionSeek = "";
        }
        console.log("区：" + this.searchMap.bRegionSeek);
    },
    onSelected(data) {
        if (data.province.code == undefined) {
            data.province.value = "";
        }
        if (data.city.code == undefined) {
            data.city.value = "";
        }
        if (data.area.code == undefined) {
            data.area.value = "";
        }
        // alert(data.province.value + ' | ' + data.city.value + ' | ' + data.area.value);
        console.log(data.province.value + ' | ' + data.city.value + ' | ' + data.area.value);
        console.log(data)
    },
    selectMedicinal() {
        console.log("基地面积：" + this.searchMap.bArea);
    },

    // 打开新增产地产区弹窗
    openNew() {
        this.isEdit = false;
        this.opendialog(this.isEdit);
    },

    // 打开选择位置弹窗
    openChoosePositon() {
        this.center.lng = 113.27324;
        this.center.lat = 23.15792;
        console.log("经度:" + this.center.lng);
        console.log("纬度:" + this.center.lat);
        this.zoom = 15;     // 放大比例
        this.positionDialog = true;
    },
    // 关闭选择位置弹窗
    closeChoosePosition() {
        map.clearOverlays();

        this.positionDialog = false;
    },
    // 确定选择的位置
    confirmPosition() {
        this.fpojo.bLongitude = this.center.lng;
        this.fpojo.bLatitude = this.center.lat;
        this.positionDialog = false;
    },
    syncCenterAndZoom() {
        const { lng, lat } = e.target.getCenter();
        this.center.lng = lng;
        this.center.lat = lat;
    },
    // 关闭编辑弹窗之前的回调
    handleDialogClose() {
        // this.fetchData();
        this.editdataDialog = false;
    },
    // 关闭编辑弹窗，并将值赋为空
    closeDialog() {
        this.editdataDialog = false;
        this.fetchData();
    },
    // 打开弹窗
    opendialog(e) {
        if (e) {
            this.fpojo = this.backup;
            // console.log("备份+++++++++++", this.backup);
            this.title = "修改基地";
        } else {
            this.title = "新增基地";
            this.fpojo = {
                id: "",
                bName: "",
                bArea: "",
                bCompanyId: "",
                bPosition: "",
                bProvince: "",
                bCity: "",
                bRegion: "",
                // 以下的省市区用来清空
                province: '',
                city: '',
                area: '',
                bLatitude: "",
                bLongitude: "",
                bRemarks: "",
                bWaterEnvironment: "",
                bSoilEnvironment: "",
                bAirEnvironment: "",
                bTotalityAppraise: "",
                bEnvironmentDataImgPath: ""
            };
        }
        this.editdataDialog = true;
        // 等渲染完成之后再清除校验规则
        this.$nextTick(() => {
            this.$refs.feditForm.cancelFieldValidate("seditForm");
        });
    },
    cancleUpload() {
        // console.log(this.backup2);
        this.closeDialog();
    },
    addData() {
        // console.log(this.fpojo);
        // this.closeDialog();
        this.$refs.feditForm.validateForm();
    },

    // 修改操作
    handleEdit(id) {
        if (id != null && id != "") {
            this.isEdit = true; // 切换为修改状态
            this.opendialog(this.isEdit);
            // this.fpojo
        } else {
            this.$message({
                message: "请选择需要修改的基地哦！",
                type: "warning"
            });
        }
    },

    // 有关上传基地图片的方法
    // 上传之前判断图片信息
    checkType(file, fileList) {
        // const isJPG = file.type === "image/jpeg";
        // const isPNG = file.type === "image/png";
        // 截取文件类型
        let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
        const isLt1M = file.size / 1024 / 1024 < 1;

        if (fileType !== "jpeg" && fileType !== "jpg" && fileType !== "png") {
            this.$message.error("上传头像图片只能是 JPG 或 PNG格式!");
        }
        if (!isLt1M) {
            this.$message.error("上传头像图片大小不能超过 1MB!");
        }
        // 确认要上传的文件
        // 确认要上传的文件
        this.headImgFile = file;
        console.log("选择的图片" + this.headImgFile.name);
        this.fileList = fileList;
        console.log(this.fileList);
    },

    // 照片移除之前
    handleRemove(file, fileList) {
        console.log(file, fileList);
        this.fileList = fileList;
        console.log(this.fileList);
    },

    // 清除选择的图片
    cleanImg() {
        this.fileList = [];
    },
    // 取消上传
    cancleUploadImg(fileList) {
        this.cleanImg();
        this.dialogUploadPhoto = false;
    },
    // 确认上传
    uploadImg() {
        let imgfile = new FormData();
        for (var i = 0; i < this.fileList.length; i++) {
            // files[i] = this.fileList[i].raw;
            imgfile.append("files", this.fileList[i].raw);
        }
        // console.log("文件长度",files.length);
        imgfile.append("id", this.radio);
        console.log("将要上传的文件：", imgfile.get("files"));
        if (this.fileList.length > 0) {
            this.$ajax({
                method: "post",
                url: "/zy-api/item/productBase/productImg",
                data: imgfile,
                headers: {
                    'token': this.$store.state.user.token
                }
            }).then(resp => {
                console.log("返回值:", resp.data.code)
                if (resp.data.code) {
                    this.$message({
                        message: "上传药材图片成功",
                        type: "success"
                    });
                } else {
                    this.$message({
                        message: "上传药材图片失败",
                        type: "warning"
                    })
                }
                this.cleanImg();
                this.dialogUploadPhoto = false;
            })
        } else {
            this.$message({
                message: "请选择需要上传的图片",
                type: "warning"
            });
        }
    },

    // 删除生产基地信息
    deleteProductBase(id) {
        if (id != null && id != "") {
            this.$confirm("此操作将永久删除该生产基地信息, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    productbaseApi.productBaseDelete(id).then(resp => {
                        if (resp.data.code == 0) {
                            this.$message({
                                message: "删除基地信息成功",
                                type: "success"
                            });
                            this.fetchData();
                            this.radio = '';
                        } else {
                            this.$message({
                                message: "删除基地信息失败",
                                type: "warning"
                            });
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
        } else {
            this.$message({
                message: "请选择需要删除的基地哦！",
                type: "warning"
            });
        }
    }


};

function created() {
    // 初始化获取列表数据
    this.fetchData();
};

function mounted() {
    setTimeout(() => {
        // document.getElementById('select-dis').firstChild.style.borderColor = '#dcdfe6';
        // document.getElementById('select-dis').getElementsByTagName('select')[1].style.borderColor = '#dcdfe6';
        // document.getElementById('select-dis').getElementsByTagName('select')[2].style.borderColor = '#dcdfe6';
        this.handleChangeDis();
    }, 10);
};

export default {
    BASEURL,
    baseArea,
    mnames,
    data,
    components,
    methods,
    created,
    mounted,
}